import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../providers/auth_provider.dart';
import '../providers/offline_mode_provider.dart';
import '../widgets/platform/adaptive_navigation.dart';
import 'home/home_page.dart';
import 'project/project_list_page.dart';
import 'todo/todo_list_page.dart';
import 'excel/excel_page.dart';
import 'spreadsheet/spreadsheet_dashboard_page.dart';
import 'requirement/requirement_list_page.dart';
import 'knowledge/knowledge_base_page.dart'; // 知识库页面
import 'note/note_list_page.dart'; // 笔记页面
// 添加离线模式状态的导入
import '../../../core/offline/offline_mode_manager.dart';
// 导入窗口管理器
import '../../../core/platform/window_manager.dart';

/// 仪表板页面，包含自适应导航
class DashboardPage extends ConsumerStatefulWidget {
  const DashboardPage({super.key});

  @override
  ConsumerState<DashboardPage> createState() => _DashboardPageState();
}

class _DashboardPageState extends ConsumerState<DashboardPage> {
  int _selectedIndex = 0;

  static final List<Widget> _pages = <Widget>[
    const HomePage(),
    const ProjectListPage(),
    const TodoListPage(),
    const RequirementListPage(), // 需求管理页面
    const KnowledgeBasePage(), // 知识库页面
    const NoteListPage(), // 笔记页面
    const ExcelPage(),
    const SpreadsheetDashboardPage(),
  ];

  static final List<NavigationDestination> _bottomDestinations =
      <NavigationDestination>[
    const NavigationDestination(
      icon: Icon(Icons.home),
      label: '首页',
    ),
    const NavigationDestination(
      icon: Icon(Icons.folder),
      label: '项目',
    ),
    const NavigationDestination(
      icon: Icon(Icons.assignment),
      label: '待办',
    ),
    const NavigationDestination(
      icon: Icon(Icons.list_alt), // 需求管理图标
      label: '需求',
    ),
    const NavigationDestination(
      icon: Icon(Icons.book), // 知识库图标
      label: '知识库',
    ),
    const NavigationDestination(
      icon: Icon(Icons.sticky_note_2), // 笔记图标
      label: '笔记',
    ),
    const NavigationDestination(
      icon: Icon(Icons.upload_file),
      label: 'Excel',
    ),
    const NavigationDestination(
      icon: Icon(Icons.table_chart),
      label: '电子表格',
    ),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  void initState() {
    super.initState();
    // 设置窗口为可调整大小
    _setResizableWindow();
  }

  // 设置窗口为可调整大小
  void _setResizableWindow() {
    WindowManager.setWindowStyle(false); // 可调整大小
    // 设置窗口为笔记本大小
    WindowManager.setWindowSize(1200, 800); // 设置窗口大小为更大的笔记本大小
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);

    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('需求管理平台'),
        actions: [
          // 离线模式切换按钮
          _buildOfflineModeButton(),
          const SizedBox(width: 16),
          // 搜索框
          _buildSearchBar(),
          const SizedBox(width: 16),
          // 通知按钮
          _buildNotificationButton(),
          const SizedBox(width: 16),
          // 用户信息
          _buildUserAvatar(currentUser),
          const SizedBox(width: 16),
        ],
      ),
      body: AdaptiveNavigation(
        selectedIndex: _selectedIndex,
        onDestinationSelected: _onItemTapped,
        destinations: _bottomDestinations,
        pages: _pages,
      ),
    );
  }

  // 构建离线模式切换按钮
  Widget _buildOfflineModeButton() {
    return Consumer(
      builder: (context, ref, child) {
        final offlineModeStatus = ref.watch(offlineModeStatusProvider);

        String getButtonText() {
          if (offlineModeStatus is AsyncData<OfflineModeStatus>) {
            switch (offlineModeStatus.value) {
              case OfflineModeStatus.online:
                return '在线';
              case OfflineModeStatus.offline:
                return '离线';
              case OfflineModeStatus.syncing:
                return '同步中';
            }
          }
          return '在线';
        }

        IconData getButtonIcon() {
          if (offlineModeStatus is AsyncData<OfflineModeStatus>) {
            switch (offlineModeStatus.value) {
              case OfflineModeStatus.online:
                return Icons.cloud_done;
              case OfflineModeStatus.offline:
                return Icons.cloud_off;
              case OfflineModeStatus.syncing:
                return Icons.sync;
            }
          }
          return Icons.cloud_done;
        }

        Color getButtonColor() {
          if (offlineModeStatus is AsyncData<OfflineModeStatus>) {
            switch (offlineModeStatus.value) {
              case OfflineModeStatus.online:
                return Colors.green;
              case OfflineModeStatus.offline:
                return Colors.orange;
              case OfflineModeStatus.syncing:
                return Colors.blue;
            }
          }
          return Colors.green;
        }

        return PopupMenuButton<String>(
          onSelected: (String value) {
            switch (value) {
              case 'online':
                ref.read(offlineModeNotifierProvider.notifier).forceOnline();
                break;
              case 'offline':
                ref.read(offlineModeNotifierProvider.notifier).forceOffline();
                break;
              case 'sync':
                ref.read(offlineModeNotifierProvider.notifier).manualSync();
                break;
            }
          },
          itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
            const PopupMenuItem<String>(
              value: 'online',
              child: Row(
                children: [
                  Icon(Icons.cloud_done, color: Colors.green),
                  SizedBox(width: 8),
                  SelectableText('切换为在线'),
                ],
              ),
            ),
            const PopupMenuItem<String>(
              value: 'offline',
              child: Row(
                children: [
                  Icon(Icons.cloud_off, color: Colors.orange),
                  SizedBox(width: 8),
                  SelectableText('切换为离线'),
                ],
              ),
            ),
            const PopupMenuItem<String>(
              value: 'sync',
              child: Row(
                children: [
                  Icon(Icons.sync, color: Colors.blue),
                  SizedBox(width: 8),
                  SelectableText('手动同步'),
                ],
              ),
            ),
          ],
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: getButtonColor().withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: getButtonColor()),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(getButtonIcon(), color: getButtonColor(), size: 16),
                const SizedBox(width: 4),
                SelectableText(
                  getButtonText(),
                  style: TextStyle(color: getButtonColor(), fontSize: 12),
                ),
                const Icon(Icons.arrow_drop_down, size: 16, color: Colors.grey),
              ],
            ),
          ),
        );
      },
    );
  }

  // 构建搜索框
  Widget _buildSearchBar() {
    return SizedBox(
      width: 250,
      child: Container(
        constraints: const BoxConstraints(maxWidth: 250),
        padding: const EdgeInsets.symmetric(horizontal: 12),
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.search, size: 18, color: Colors.grey),
            const SizedBox(width: 8),
            Expanded(
              child: TextField(
                decoration: const InputDecoration(
                  hintText: '搜索需求、提需人、组织...',
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.zero,
                  isDense: true,
                ),
                style: const TextStyle(fontSize: 14),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建通知按钮
  Widget _buildNotificationButton() {
    return SizedBox(
      width: 48,
      height: 48,
      child: Stack(
        children: [
          IconButton(
            icon: const Icon(Icons.notifications_none),
            onPressed: () {
              // 通知页面导航
            },
            iconSize: 24, // 设置图标大小
          ),
          Positioned(
            right: 8,
            top: 8,
            child: Container(
              width: 16,
              height: 16,
              decoration: const BoxDecoration(
                color: Colors.red,
                shape: BoxShape.circle,
              ),
              child: Center(
                child: SelectableText(
                  '3',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 10,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建用户头像
  Widget _buildUserAvatar(dynamic currentUser) {
    return PopupMenuButton<String>(
      onSelected: (value) {
        switch (value) {
          case 'settings':
            // 个人设置
            context.push('/settings');
            break;
          case 'logout':
            _handleLogout(context, ref);
            break;
        }
      },
      itemBuilder: (context) => [
        const PopupMenuItem(
          value: 'settings',
          child: Row(
            children: [
              Icon(Icons.settings, size: 16),
              SizedBox(width: 8),
              Text('个人设置'),
            ],
          ),
        ),
        const PopupMenuItem(
          value: 'logout',
          child: Row(
            children: [
              Icon(Icons.logout, size: 16),
              SizedBox(width: 8),
              Text('退出登录'),
            ],
          ),
        ),
      ],
      child: SizedBox(
        width: 120, // 添加固定宽度以避免无限宽度问题
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircleAvatar(
              radius: 16,
              backgroundColor: Theme.of(context).primaryColor,
              child: Text(
                currentUser?.username.substring(0, 1).toUpperCase() ?? 'U',
                style: const TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            const SizedBox(width: 8),
            Flexible(
              child: Text(
                currentUser?.username ?? '用户',
                style: const TextStyle(
                  overflow: TextOverflow.fade,
                ),
              ),
            ),
            const Icon(Icons.arrow_drop_down, size: 16),
          ],
        ),
      ),
    );
  }

  void _handleLogout(BuildContext context, WidgetRef ref) {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认退出'),
        content: const Text('您确定要退出登录吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 询问用户是否保留本地认证数据以支持离线登录
              _showKeepLocalDataDialog(context, ref);
            },
            child: const Text('确认'),
          ),
        ],
      ),
    );
  }

  void _showKeepLocalDataDialog(BuildContext context, WidgetRef ref) {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('登出选项'),
        content: const Text(
            '请选择登出方式：\n\n- 保留本地数据：仅登出服务器账户，保留本地认证信息以支持离线登录\n- 清除所有数据：完全清除认证信息，包括本地数据'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 保留本地数据，仅登出服务器账户
              ref.read(authStateProvider.notifier).logout();
              context.go('/login');
            },
            child: const Text('保留本地数据'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 清除所有数据
              ref.read(authStateProvider.notifier).logout(clearLocalData: true);
              context.go('/login');
            },
            child: const Text('清除所有数据'),
          ),
        ],
      ),
    );
  }
}
